// eslint-disable-next-line import/named
import { ActionTree } from 'vuex'
import { StateInterface } from '../state'
import { ToolStateInterface } from './state'
import iTool from 'src/api/tool'
import iUser from 'src/api/user'

const actions: ActionTree<ToolStateInterface, StateInterface> = {
  async initTag ({
    commit,
    state
  }) {
    // 获取标签列表
    if (state.tag.isLoaded) return
    const tagList = await iTool.findAllTags({})
    commit('setTagList', tagList)
  },
  async initTool ({ commit }, {
    ids,
    keywords,
    sorts
  }: { ids: string[], keywords?: string, sorts: string }) {
    const tools = await iTool.findTools({
      tags: (ids || []).filter(e => e),
      keywords,
      sorts
    })
    commit('setToolList', tools)
    commit('syncToolWithUser')
  },
  async initUserTool ({ commit }, ids: string[]) {
    ids = ids || []
    if (ids) {
      const tools = await iTool.getToolByIds({
        ids: ids
      })
      commit('setToolList', tools)
      commit('syncToolWithUser')
    }
  },
  async initCurrentTool ({ commit }, id) {
    const tools = await iTool.getToolByIds({
      ids: [id]
    })
    commit('setCurrentTool', tools[0])
    commit('syncToolWithUser')
  },
  async addToolLike ({ commit }, tool) {
    const id = tool._id
    await iUser.postActivity({
      level: 1,
      type: 2,
      location: {
        module: 'apps',
        page: 'tool',
        element: 'vote-icon',
        event: 'click'
      },
      action: '@tool/like',
      value: { id: id }
    })
    commit('pushToolLike', tool)
    commit('syncToolWithUser')
  },
  async popToolLike ({ commit }, tool) {
    const id = tool._id
    await iUser.postActivity({
      level: 1,
      type: 2,
      location: {
        module: 'apps',
        page: 'tool',
        element: 'vote-icon',
        event: 'click'
      },
      action: '@tool/cancel-like',
      value: { id: id }
    })
    commit('popToolLike', tool)
    commit('syncToolWithUser')
  },
  async addToolCollection ({ commit }, tool) {
    const id = tool._id
    await iUser.postActivity({
      level: 1,
      type: 2,
      location: {
        module: 'apps',
        page: 'tool',
        element: 'collect-icon',
        event: 'click'
      },
      action: '@tool/collection',
      value: { id: id }
    })
    commit('pushToolCollection', tool)
    commit('syncToolWithUser')
  },
  async removeToolCollection ({ commit }, tool) {
    const id = tool._id
    await iUser.postActivity({
      level: 1,
      type: 2,
      location: {
        module: 'apps',
        page: 'tool',
        element: 'collect-icon',
        event: 'click'
      },
      action: '@tool/collectionRemove',
      value: { id: id }
    })
    commit('deleteToolCollection', tool)
    commit('syncToolWithUser')
  }
}
export default actions
